<template>
  <div class="year-range-picker">
    <el-date-picker
      v-model="startYear"
      type="year"
      placeholder="选择开始年"
      size="mini"
      class="year-picker"
      @change="changeStartYear"
      format="yyyy"
      value-format="yyyy"
      :picker-options="{
        disabledDate(time) {
          // 判断时间是否在当前时间之后，如果是，则返回false，否则返回true（禁用）
          return time.getTime() > new Date().getTime()
        },
      }"
    >
    </el-date-picker>
    <span class="range-word"> 至 </span>
    <el-date-picker
      v-model="endYear"
      type="year"
      placeholder="选择结束年"
      size="mini"
      class="year-picker"
      @change="changeEndYear"
      format="yyyy"
      value-format="yyyy"
      :picker-options="{
        disabledDate(time) {
          // 判断时间是否在当前时间之后，如果是，则返回false，否则返回true（禁用）
          return time.getTime() > new Date().getTime()
        },
      }"
    >
    </el-date-picker>
  </div>
</template>

<script>
export default {
  name: 'YearRangePicker',
  // 接收父组件传入的数据
  props: {
    yearRange: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      startYear: '',
      endYear: '',
    }
  },
  mounted() {
    // 初始化自身变量
    this.startYear = String(this.yearRange[0])
    this.endYear = String(this.yearRange[1])
  },
  methods: {
    changeStartYear(val) {
      // 开始年份大于结束年份，调换
      if (Number(this.startYear) > Number(this.endYear)) {
        this.startYear = this.endYear
        this.endYear = val
      }
      // 将改动传回父组件
      this.$emit('yearChanged', [Number(this.startYear), Number(this.endYear)])
    },
    changeEndYear(val) {
      if (Number(this.startYear) > Number(this.endYear)) {
        this.endYear = this.startYear
        this.startYear = val
      }
      this.$emit('yearChanged', [Number(this.startYear), Number(this.endYear)])
    },
  },
}
</script>

<style scoped>
.year-range-picker {
  font-size: 14px;
  color: #606266;
  text-align: center;
}

.range-word {
  margin-left: 10px;
  margin-right: 10px;
}

.year-range-picker .year-picker {
  max-width: 160px;
}
</style>
